﻿using BLToolkit.Data;
using BLToolkit.Data.Linq;
using SettlersAuto.Data;
using SettlersAuto.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SettlersAuto.Web.Controllers
{
    public partial class SystemController : Controller
    {
        //
        // GET: /System/

        public virtual ActionResult Index()
        {
            return View();
        }

        public virtual ActionResult ReparseLatest()
        {
            using (var db = new SettlersAutoDb())
            {
                var session = db.TradeSessions
                    .OrderByDescending(s => s.Timestamp)
                    .FirstOrDefault();

                if (session == null)
                {
                    ViewBag.Message = "There is no sessions with data.";
                    return View("Index");
                }

                db.TradeSlots.Delete(ts => ts.TradeSessionId == session.TradeSessionId);
                ReparseSession(db, session);

                return View("Index");
            }
        }

        public virtual ActionResult ReparseAll()
        {
            using (var db = new SettlersAutoDb())
            {
                var sessions = db.TradeSessions
                    .OrderByDescending(s => s.Timestamp)
                    .Where(s => s.RawData != null)
                    .ToList();

                db.TradeSlots.Delete();
                foreach (var session in sessions)
                {
                    ReparseSession(db, session);
                }

                ViewBag.Message = "Reparsed successfully.";
                return View("Index");
            }
        }

        private void ReparseSession(SettlersAutoDb db, TradeSession session)
        {
            //var slots = DataImport.ParseTradeSlots(session.RawData);
            //foreach (var slot in slots)
            //{
            //    slot.TradeSessionId = session.TradeSessionId;
            //    db.InsertOrReplace(slot);
            //}
        }
    }
}
